import React, { useState, useEffect } from "react";
import collect from "../style/collect.module.css";
import { home } from "../api/home";
import { Me_mystar } from "../api/me";
import { useNavigate } from "react-router-dom";
import leftImg from "../img/left.png";

interface ProductItem {
  id: string | number;
  img: string;
  title: string;
  synopsis: string;
  price: string;
}
interface Product {
  id: number;
  title?: string;
  synopsis?: string;
  price: number | string;
  original_price?: number | string;
  img?: string;
}
interface ApiResponse {
  data: {
    recommend: ProductItem[];
    list?: Product[];
  };
}
function CollectPage() {
  const navigate = useNavigate();
  // 使用更稳定的user解析方式
  const user = JSON.parse(localStorage.getItem("user") || "{}");
  const [shouShop, setShouShop] = useState<ProductItem[]>([]);
  const [shopList, setShopList] = useState<Product[]>([]);
  // 请求收藏接口
  useEffect(() => {
    if (user?.data?.id && user?.data?.token) {
      Me_mystar(
        { uid: user.data.id }, // 第一个参数：data
        { Authorization: user.data.token } // 第二个参数：headers
      )
        .then((res) => {
          console.log("完整接口返回数据:", res.data); // 打印完整数据

          // 检查 res.data.data 是否存在
          const recommendData = res.data.data?.recommend || [];
          console.log("接口返回数据:", recommendData);

          // 如果数据为空，提示用户
          if (recommendData.length === 0) {
            console.log("用户没有收藏数据");
          }

          // 修复2：避免不必要的数据更新
          if (JSON.stringify(recommendData) !== JSON.stringify(shouShop)) {
            setShouShop(recommendData);
          }
        })
        .catch((error) => {
          console.error("请求出错:", error);
        });
    }
  }, [user?.data?.id, user?.data?.token]); // 关键依赖项
  useEffect(() => {
    fetchShopList();
  }, []);

  // 为你推荐列表

  const fetchShopList = async () => {
    try {
      // 检查 user.data 是否存在
      if (!user?.data?.token || !user?.data?.id) {
        console.error("用户数据不存在或 token/id 为空");
        return;
      }

      // 发送请求
      const res = await home({
        headers: {
          token: user.data.token,
          id: user.data.id,
        },
      });
      console.log("请求结果:", res);

      // 检查返回数据
      if (res.data && Array.isArray(res.data.data.list)) {
        setShopList(res.data.data.list);
      } else {
        console.error("返回数据格式不符合预期:", res.data);
        setShopList([]);
      }
    } catch (error) {
      console.error("获取推荐商品失败:", error);
    }
  };
  const goBack = () => navigate(-1);

  const handleItemClick = (id: string | number) => {
    localStorage.setItem("productId", id.toString());
    navigate("/detail");
  };

  return (
    <div className={collect.collect}>
      <div className={collect.top}>
        <div>
          <img onClick={goBack} src={leftImg} alt="" />
          <b>商品收藏</b>
        </div>
      </div>

      <div className={collect.noProducts}>
        {shouShop.length > 0 ? (
          shouShop.map((item) => (
            <div
              key={item.id}
              className={collect.item}
              onClick={() => handleItemClick(item.id)}
            >
              <div className={collect.item_img}>
                <img src={item.img} alt="" />
              </div>
              <div className={collect.item_family}>
                <div className={collect.item_title}>{item.title}</div>
                <div className={collect.item_synopsis}>{item.synopsis}</div>
                <div className={collect.item_red}>{item.price}</div>
              </div>
            </div>
          ))
        ) : (
          <div>暂无收藏商品</div>
        )}
      </div>

      <div className={collect.three}>
        <div></div>
        <p>为您推荐</p>
        <div></div>
      </div>

      {/* 推荐商品保持原有属性名 */}
      <div className={collect.recommend}>
        <div className={collect.shop}>
          {shopList.map((product) => (
            <div
              key={product.id}
              className={collect.shop_item}
              onClick={() => handleItemClick(product.id)}
            >
              <img
                src={product.img || "./img/head.jpg"}
                alt={product.title || "商品"}
              />
              <p>{product.title || "商品名称"}</p>
              <span>{product.synopsis || "商品描述"}</span>
              <div className={collect.items}>
                <p>￥{Number(product.price).toFixed(2)}</p>
                {typeof product.original_price === "number" && (
                  <del>￥{product.original_price.toFixed(2)}</del>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

export default CollectPage;
